package com.benefm.multipar.pad.http;

import android.util.Log;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;

public class LogInterceptor implements Interceptor {

    public static final String TAG = LogInterceptor.class.getSimpleName();

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Log.i(TAG, "request url == " + request.url());

        RequestBody requestBody = request.body();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            String paramsJson = buffer.readUtf8();
            Gson gson = new Gson();
            //获取原始参数
            HashMap<String, Object> rootMap = gson.fromJson(paramsJson, HashMap.class);
            if (rootMap != null) {
                Log.i(TAG, "request json == " + gson.toJson(rootMap));
            }
        }

        long startTime = System.currentTimeMillis();
        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();

        Log.i(TAG, "------------------------end:" + duration + "毫秒------------------------");
        Log.i(TAG, "response data  == " + content + " \n ");
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }
}